<!--
 * @Author: your name
 * @Date: 2022-01-17 22:08:12
 * @LastEditTime: 2022-02-14 14:24:58
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-element-admin\src\views\crm\Linkman.vue
-->
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="addShow()"
        >添加合同</el-button
      >
    </div>

    <TableGeneral
      :tableData="tableData"
      :tableColumn="tableColumn"
      :loading="tableLoading"
      :tableConfig="{ stripe: true }"
      @refresh="tableLoad"
      @search="search"
    >
      <!-- <div slot="status" slot-scope="{ scopeRow }">
        <el-tag v-show="scopeRow.status == 1" type="success"> 启用</el-tag>
        <el-tag v-show="scopeRow.status == 0" type="danger"> 禁用</el-tag>
      </div> -->

      <div slot="convertible_assets" slot-scope="{ scopeRow }">
        <el-tag v-show="scopeRow.convertible_assets == 1"> 是</el-tag>
        <el-tag v-show="scopeRow.convertible_assets == 0" type="warning">
          否</el-tag
        >
      </div>
      <div slot="nickName" slot-scope="{ scopeRow }">
        <span>{{
          `${scopeRow.nickName}${
            scopeRow.realName ? "(" + scopeRow.realName + ")" : ""
          }`
        }}</span>
      </div>
      <div slot="operation" slot-scope="{ scopeRow }">
        <el-button type="text" size="small" @click="edit(scopeRow)">
          编辑
        </el-button>

        <el-popconfirm
          title="确定要禁用吗"
          @confirm="editObj(scopeRow.id, { status: 0 })"
          v-show="scopeRow.status == 1"
        >
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >禁用</el-button
          >
        </el-popconfirm>
        <el-popconfirm
          title="确定要启用吗"
          @confirm="editObj(scopeRow.id, { status: 1 })"
          v-show="scopeRow.status == 0"
        >
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >启用</el-button
          >
        </el-popconfirm>
        <!-- <template> -->

        <el-popconfirm title="确定要删除吗" @confirm="delOne(scopeRow.id)">
          <!-- <div> -->
          <el-button
            slot="reference"
            type="text"
            size="small"
            style="margin-left: 10px"
            >删除</el-button
          >
        </el-popconfirm>
      </div>
    </TableGeneral>

    <div class="pagination">
      <el-pagination
        background
        layout="sizes,total,prev, pager, next"
        :page-size="config.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="sizeChange"
        :total="tableCount"
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加合同 -->
    <el-dialog
      :title="`${edit_id ? '编辑' : '添加'}合同`"
      :visible.sync="dialogFormVisible"
      @closed="closed"
    >
      <div class="dialogCenter">
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          v-loading="formLoading"
        >
          <el-form-item label="主题" :label-width="formLabelWidth" prop="theme">
            <el-input v-model="form.theme" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="客户"
            :label-width="formLabelWidth"
            prop="customer_id"
          >
            <!-- <el-input v-model="form.customer_id" autocomplete="off"></el-input> -->
            <el-select
              v-model="form.customer_id"
              placeholder="请选择客户"
              filterable
            >
              <!-- 执行中 结束 意外中止 -->
              <el-option
                :label="`${item.company_name} (${item.id})`"
                :value="item.id.toString()"
                v-for="(item, index) in customerSelList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="产品"
            :label-width="formLabelWidth"
            prop="product_id"
          >
            <el-select
              v-model="form.product_id"
              placeholder="请选择产品"
              filterable
            >
              <!-- 执行中 结束 意外中止 -->
              <el-option
                :label="`${item.product_name} (${item.id})`"
                :value="item.id.toString()"
                v-for="(item, index) in productSelList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="总金额"
            :label-width="formLabelWidth"
            prop="total_amount"
          >
            <el-input
              v-model="form.total_amount"
              autocomplete="off"
              style="width: 200px"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="所属部门" :label-width="formLabelWidth">
            <TreeSelct
              :props="{ value: 'id', label: 'name', children: 'children' }"
              :options="treeData"
              :accordion="true"
              :clearable="true"
              :value="division_id.toString()"
              :key="'TreeSelct' + division_id"
              ref="treeSelct"
              v-if="!treeDataLoading"
            />
          </el-form-item>
          <el-form-item label="合同所有人" :label-width="formLabelWidth">
            {{
              `${linkmanBelong.nickName}${
                linkmanBelong.realName ? "(" + linkmanBelong.realName + ")" : ""
              }`
            }}
          </el-form-item>
          <el-form-item
            label="销售机会"
            :label-width="formLabelWidth"
            prop="sales_opportunities"
          >
            <el-input v-model="form.sales_opportunities" autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item
            label="合同类型"
            :label-width="formLabelWidth"
            prop="contract_type"
          >
            <el-input v-model="form.contract_type" autocomplete="off">
            </el-input>
          </el-form-item>
          <el-form-item
            label="合同状态"
            :label-width="formLabelWidth"
            prop="contract_states"
          >
            <el-select
              v-model="form.contract_states"
              placeholder="请选择合同状态"
              clearable
            >
              <!-- 执行中 结束 意外中止 -->
              <el-option label="执行中" value="执行中"></el-option>
              <el-option label="结束" value="结束"></el-option>
              <el-option label="意外中止" value="意外中止"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="付款方式"
            :label-width="formLabelWidth"
            prop="payment_method"
          >
            <el-select
              v-model="form.payment_method"
              placeholder="请选择付款方式"
              clearable
            >
              <el-option label="支票" value="支票"></el-option>
              <el-option label="现金" value="现金"></el-option>
              <el-option label="银行转账" value="银行转账"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="开始日期"
            :label-width="formLabelWidth"
            prop="start_time"
          >
            <el-input
              v-model="form.start_time"
              autocomplete="off"
              style="width: 200px"
              type="date"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            label="结束日期"
            :label-width="formLabelWidth"
            prop="end_time"
          >
            <el-input
              v-model="form.end_time"
              autocomplete="off"
              style="width: 200px"
              type="date"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            label="合同正文"
            :label-width="formLabelWidth"
            prop="body_contract"
          >
            <el-input
              type="textarea"
              v-model="form.body_contract"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="客户方签约人"
            :label-width="formLabelWidth"
            prop="customer_contractor"
          >
            <el-input
              v-model="form.customer_contractor"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="我方签约人"
            :label-width="formLabelWidth"
            prop="mine_contractor"
          >
            <el-input
              v-model="form.mine_contractor"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="签约日期"
            :label-width="formLabelWidth"
            prop="contractor_date"
          >
            <el-input
              v-model="form.contractor_date"
              autocomplete="off"
              type="date"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="合同备注"
            :label-width="formLabelWidth"
            prop="remark"
          >
            <el-input
              type="textarea"
              v-model="form.remark"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" v-loading="formLoading">
        <el-button @click="reset('form')" v-show="!edit_id">重置</el-button>

        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="`跟进情况`"
      :visible.sync="followUpObj.visible"
      width="70%"
    >
      <div class="dialogCenter">
        <ChangeableTable
          ref="changeableTable"
          :tableColumn="followUpObj.changeColumn"
          :loading="followUpObj.loading"
          :tableData="followUpObj.tableData"
        />
      </div>
      <div slot="footer" class="dialog-footer" v-loading="followUpObj.loading">
        <!-- <el-button @click="reset('form')">重置</el-button> -->

        <el-button type="primary" @click="ableSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const tableColumn = [
  {
    dataIndex: "id",
    width: "100",
    title: "ID",
    returnField: "like-crm_contract-id",
  },
  {
    dataIndex: "theme",
    width: "220",
    title: "主题",
    returnField: "like-crm_contract-theme",
  },
  {
    dataIndex: "customer_company_name",
    width: "220",
    title: "所属客户(公司名称)",
    returnField: "like-crm_customer-company_name",
  },
  {
    dataIndex: "product_name",
    width: "220",
    title: "产品名称",
    returnField: "like-crm_product-product_name",
  },
  {
    dataIndex: "division_name",
    width: "220",
    title: "所属部门",
    returnField: "like-chain-division_name",
  },
  {
    dataIndex: "total_amount",
    width: "220",
    title: "总金额",
    returnField: "like-crm_contract-total_amount",
  },
  {
    scopedSlots: "nickName",
    width: "220",
    title: "合同负责人",
    manyField: ["like-admins-nickName", "like-admins-realName"],
  },
  {
    scopedSlots: "sales_opportunities",
    width: "220",
    title: "销售机会",
    returnField: "like-crm_product-sales_opportunities",
  },
 {
    scopedSlots: "contract_type",
    width: "220",
    title: "合同类型",
    returnField: "like-crm_product-contract_type",
  },
 {
    scopedSlots: "contract_states",
    width: "220",
    title: "合同状态",
    returnField: "equal-crm_product-contract_states",
    dataType: "select",
    selectOptions: [
      {
        title: "执行中",
        value: "执行中",
      },
      {
        title: "结束",
        value: "结束",
      },
      {
        title: "意外中止",
        value: "意外中止",
      },
    ],
  },
 {
    scopedSlots: "payment_method",
    width: "220",
    title: "付款方式",
    returnField: "equal-crm_product-payment_method",
    dataType: "select",
    //支票 现金 银行转账 其他
    selectOptions: [
      {
        title: "支票",
        value: "支票",
      },
      {
        title: "现金",
        value: "现金",
      },
      {
        title: "银行转账",
        value: "银行转账",
      },
       {
        title: "其他",
        value: "其他",
      }
    ],
  },
  {
    dataIndex: "start_time",
    width: "220",
    title: "开始日期",
    returnField: "like-crm_product-start_time",
  },
   {
    dataIndex: "end_time",
    width: "220",
    title: "结束日期",
    returnField: "like-crm_product-end_time",
  },
   {
    dataIndex: "body_contract",
    width: "300",
    title: "合同正文",
    returnField: "like-crm_product-body_contract",
  },
    {
    dataIndex: "contract_no",
    width: "220",
    title: "合同编号",
    returnField: "like-crm_product-contract_no",
  },
    {
    dataIndex: "customer_contractor",
    width: "220",
    title: "客户方签约人",
    returnField: "like-crm_product-customer_contractor",
  },
  {
    dataIndex: "mine_contractor",
    width: "220",
    title: "我方签约人",
    returnField: "like-crm_product-mine_contractor",
  },
  {
    dataIndex: "contractor_date",
    width: "220",
    title: "签约日期",
    returnField: "like-crm_product-contractor_date",
  },
  {
    dataIndex: "remark",
    width: "300",
    title: "备注",
    returnField: "like-crm_product-remark",
  },
  {
    scopedSlots: "operation",
    width: "180",
    title: "操作",
    position: "right",
    noSearch: 1,
  },
  // { dataIndex: "remark", width: "250", title: "备注" },
];

const formOriginal = () => {
  return {
    theme: null,
    customer_id: null,
    product_id: null,
    // admins_id:null,
    total_amount: null,
    division_id: null,
    sales_opportunities: null,
    contract_type: null,
    contract_states: null,
    payment_method: null,
    start_time: null,
    end_time: null,
    body_contract: null,
    contract_no: null,
    customer_contractor: null,
    mine_contractor: null,
    contractor_date: null,
    remark: null,
  };
};

const changeColumn = [
  {
    dataType: "textarea",
    title: "跟进日期",
    prop: "date",
    width: "200px",
  },
  {
    dataType: "textarea",
    title: "跟进人",
    prop: "name",
    width: "200px",
  },
  {
    dataType: "text",
    title: "跟进状态",
    prop: "state",
    width: "120px",
  },
  {
    dataType: "textarea",
    title: "跟进描述",
    prop: "describe",
  },
];

import TreeSelct from "@/components/TreeSelct";
import TableGeneral from "@/components/TableGeneral";
import ChangeableTable from "@/components/ChangeableTable";
import { mapActions, mapState } from "vuex";
import { validDecimal } from "@/utils/validate";

export default {
  name: "ComplexTable",
  components: {
    TreeSelct,
    TableGeneral,
    ChangeableTable,
  },
   authorize:{
    'addShow':'添加',
    'edit':'编辑',
    'delOne':'删除',
    'editObj':'编辑'
  },
  data() {
    return {
      dialogFormVisible: false,
      form: formOriginal(),
      formLabelWidth: "120px",
      treeDataLoading: true,
      tableLoading: true,
      formLoading: false,
      division_id: 0,
      treeData: [],
      edit_id: 0,
      linkmanBelong: {},
      config: {
        pageSize: 20,
        page: 1,
        keyWord: {},
      },
      rules: {
        theme: [
          { required: true, message: "主题不为空", trigger: "blur" },
          { max: 255, message: "主题长度不超过255字符", trigger: "blur" },
        ],
        customer_id: [
          { required: true, message: "客户不为空", trigger: "blur" },
        ],
        product_id: [
          { required: true, message: "产品不为空", trigger: "blur" },
        ],
        total_amount: [
          { required: true, message: "总金额不为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value == null || value == "" || validDecimal(value)) {
                callback();
              } else {
                callback(new Error("总金额最多两位小数的数字"));
              }
            },
            trigger: "blur",
          },
        ],
      },
      tableData: [],
      tableColumn: tableColumn,
      tableCount: 0,
      // imagesArray: [],
      followUpObj: {
        visible: false,
        changeColumn: changeColumn,
        loading: false,
        tableData: [],
        target_id: "", //联系人id
        followUp_id: "", //沟通记录表id
      },
      productSelList: [],
      customerSelList: [],
    };
  },
  created() {
    this.divisionListLoad();
    this.tableLoad();
    this.productListLoad();
    this.customerListLoad();
    this.division_id = this.online_msg.division_id;
  },
  watch: {},
  computed: {
    ...mapState("user", ["online_msg"]),
  },

  methods: {
    ...mapActions("division", ["divisionList"]),
    ...mapActions("contract", [
      "contractAdd",
      "contractEdit",
      "contractSelOne",
      "contractList",
    ]),
    ...mapActions("customer", [
      //   "linkmanAdd",
      //   "linkmanEdit",
      "customerList",
      //   "linkmanSelOne",
    ]),
    ...mapActions("product", [
      //   "productAdd",
      //   "productEdit",
      "productList",
      //   "productSelOne",
    ]),
    ...mapActions("upload", ["manyFile"]),

    closed() {
      this.edit_id = "";
      this.form = formOriginal();
      this.division_id = this.online_msg.division_id;

      this.$refs.treeSelct.reset();
      this.$refs.form.clearValidate()

    },
    addShow() {
      this.linkmanBelong = {
        nickName: this.online_msg.nickName,
        realName: this.online_msg.realName,
      };
      //   this.admins_id = this.online_msg.id
      this.dialogFormVisible = true;
    },
    reset(formName) {
      this.$refs[formName].resetFields();
      this.$refs.treeSelct.reset();
    },
    async customerListLoad() {
      // this.tableLoading = true;
      let res = await this.customerList();
      if (res.code == 200) {
        const { list } = res.data;
        this.customerSelList = list;
        // this.tableCount = total;
      }
      // this.tableLoading = false;
    },
    async tableLoad() {
      this.tableLoading = true;
      let res = await this.contractList(this.config);
      if (res.code == 200) {
        const { list, total } = res.data;
        this.tableData = list;
        this.tableCount = total;
      }
      this.tableLoading = false;
    },
    async productListLoad() {
      //   this.tableLoading = true;
      let res = await this.productList();
      if (res.code == 200) {
        const { list } = res.data;
        this.productSelList = list;
      }
      //   this.tableLoading = false;
    },
    search(e) {
      //  console.log(e)
      this.config.keyWord = e;
      this.tableLoad();
    },
    async edit(scopeRow) {
      this.dialogFormVisible = true;
      this.formLoading = true;
      this.edit_id = scopeRow.id;
      let res = await this.contractSelOne({ id: scopeRow.id });
      if (res.code == 200) {
        Object.keys(this.form).forEach(
          (item) => (this.form[item] = res.data[item])
        );
        this.division_id = this.form.division_id;

        this.linkmanBelong = {
          nickName: scopeRow.nickName,
          realName: scopeRow.realName,
        };

        this.formLoading = false;
      }
    },
    async delOne(id) {
      this.tableLoading = true;
      let res = await this.contractEdit({
        formData: { delete_time: this.sysTime() },
        conditions: { id: id },
      });
      if (res.code == 200) {
        this.$message.success("删除成功");
      }
      this.tableLoad();
    },
    async editObj(id, obj) {
      this.tableLoading = true;
      let res = await this.contractEdit({
        formData: obj,
        conditions: { id: id },
      });
      if (res.code == 200) {
        this.$message.success("修改成功");
      }
      this.tableLoad();
    },

    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm(
            "确定要" + (this.edit_id ? "编辑" : "添加") + "吗?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
      this.formLoading = true;

              let form = JSON.parse(JSON.stringify(this.form));
              form.division_id = this.$refs.treeSelct.valueId;
              form.admins_id = this.online_msg.id;

              if (this.edit_id) {
                delete form.admins_id;
                var res = await this.contractEdit({
                  formData: form,
                  conditions: { id: this.edit_id },
                });
              } else {
                var res = await this.contractAdd({ formData: form });
              }

              if (res.code == 200) {
                this.$message.success(res.message);
                this.dialogFormVisible = false;
                this.tableLoad();
              }
      this.formLoading = false;

            })
            
            .catch(() => {});
        } else {
          // console.log('error submit!!');
          this.$message.error("信息填写错误");
          return false;
        }
      });
    },
    currentChange(e) {
      this.config.page = e;
      this.tableLoad();
    },
    sizeChange(e) {
      this.config.pageSize = e;
      this.tableLoad();
    },
    async divisionListLoad() {
      this.treeDataLoading = true;
      let res = await this.divisionList({ "equal-crm_division-status": 1 });
      if (res.code == 200) {
        // this.treeData[0] = { name: "全公司", id: 0, children: [] };
        this.treeData = res.data.list;
        this.treeDataLoading = false;
      }
    },
  },
};
</script>
<style scoped lang="less">
.dialogCenter {
  height: 60vh;
  overflow-y: scroll;
  padding: 10px;
}
.pagination {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
</style>
